//
//  ImManager.m
//  CustomerServer
//
//  Created by 涂俊 on 2019/6/20.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "ImManager.h"
#import "HelpDeskLite/HDClient.h"
#import "ArgumentStore.h"

@interface ImManager() <HDChatManagerDelegate>
@property(nonatomic, strong)NSLock *lock;
@end

@implementation ImManager


//单例
static ImManager *instance = nil;
static NSString *IM_RECEIVE_MESSAGE = @"im_receive_message";

+ (instancetype)getInstance {
  if (instance == nil) {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
      instance = [[self alloc] init];
    });
  }
  return instance;
}

- (id)init {
  if (self = [super init]) {
    //进入聊天界面需要绑定im服务号
    [[HDClient sharedClient].chatManager bindChatWithConversationId:[ArgumentStore.current conversationId]];
    [[HDClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
  }
  return self;
}

#pragma mark - public api

//添加接收im消息的回调
- (void)addImMessageObserver:(id)notificationObserver selector:(SEL)notificationSelector {
  [[NSNotificationCenter defaultCenter] addObserver:notificationObserver selector:notificationSelector name:IM_RECEIVE_MESSAGE object:nil];
}

// 登录环信
- (BOOL) imLoginWithUsername:(NSString *)username password:(NSString *)password {
//  [NSThread sleepForTimeInterval:5];//TODO test
  HDError *error = [[HDClient sharedClient] loginWithUsername:username password:password];
  if (!error) {
    //IM登录成功
    NSLog(@"IM登录成功");
    [ArgumentStore.current setImLoginResult:@"ok"];
    return YES;
  } else {
    if (error.code == HDErrorUserAlreadyLogin) {
      // 已经登录
      NSLog(@"IM已经登录");
      [ArgumentStore.current setImLoginResult:@"ok"];
      return YES;
    } else {
      //登录失败
      NSLog(@"IM登录失败 error code :%d,error description:%@",error.code,error.errorDescription);
      [ArgumentStore.current setImLoginResult:@"fail"];
      return NO;
    }
  }
}

// 登出环信
- (BOOL) imLogout {
  HDError *error = [[HDClient sharedClient] logout:YES];
  if (!error) {
    //登出成功
    NSLog(@"登出成功");
    [ArgumentStore.current setImLoginResult:@"fail"];
    return YES;
  } else {
    //登出失败
    NSLog(@"登出失败 error code :%d,error description:%@",error.code,error.errorDescription);
    return NO;
  }
}

// 获取环信未读消息数量
-(NSNumber *)getUnreadMsgNum {
  HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:[ArgumentStore.current conversationId]];
  NSNumber *num = [NSNumber numberWithInt:conversation.unreadMessagesCount];
  NSLog(@"unreadMsgNum, num=%@", num);
  return num;
}

#pragma mark - HDChatManagerDelegate callback 环信回调

// 统一接收环信普通消息
- (void)messagesDidReceive:(NSArray *)aMessages {
  NSLog(@"messagesDidReceive, msg=%@", aMessages);
  [[NSNotificationCenter defaultCenter] postNotificationName:IM_RECEIVE_MESSAGE object:aMessages];
}

// 统一接收环信Cmd消息
- (void)cmdMessagesDidReceive:(NSArray *)aCmdMessages {
  NSLog(@"cmdMessagesDidReceive, msg=%@", aCmdMessages);
}

//消息的状态修改，一般可以用来刷新列表，显示最新的状态
- (void)messageStatusDidChange:(HDMessage *)aMessage error:(HDError *)aError {
  NSLog(@"messageStatusDidChange, msg=%@", aMessage);
}

@end
